var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var stylus = require('stylus');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var redis = require('redis');


var db = redis.createClient();
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.engine('jade', require('jade').__express);
app.engine('html', require('ejs').renderFile);

app.use(logger('dev'));
app.use(express.json()); // json???
app.use(express.urlencoded({ extended: false }));  // 编码???
app.use(cookieParser()); // 预处理cookie???
app.use(stylus.middleware(path.join(__dirname, 'public'))); // 处理stylus文件???
app.use(express.static(path.join(__dirname, 'public'))); // 静态资源???

app.use('/', indexRouter);  // 处理路由
app.use('/users', usersRouter);  // 

// 自定义中间件,除最后外应next(val)保证运行后续的中间件
// 返回404
app.use(function (req, res, next) {
  next(createError(404));
});

// 错误处理,定义在所有中间件之后
app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  res.status(err.status || 500);
  res.render('error');
});

app.listen(3000);


module.exports = app;
